<template>
	<view class="page-box">
		<view class="bg-top">
			<uni-nav-bar ref="navBar" statusBar :border="false" @clickLeft="goBack" backgroundColor="transparent" left-width="36px">
				<template v-slot:left>
					<image class="size-32" src="@/static/svg/icon-back.svg"/>
				</template>
				<template>
					<view class="flex item-center justify-center text-bold w-full">{{ groupData.groupName }}</view>
				</template>
			</uni-nav-bar>
		</view>
		<view class="top-tip flex item-center justify-between my-10 mx-16">
			<view class="fs-12">共<text class="text-red text-lg">{{ total }}</text>人<text v-if="groupData.defaultState != 2">（分组佣金<text class="text-red">{{ groupData.commissionRate }}%</text>）</text></view>
			<view class="invite-btn" @click="invite">邀请经纪人</view>
		</view>
		<view class="search-box flex item-center justify-between">
			<view class="flex item-center">
				<image src="@/static/svg/icon-search.svg" mode="heightFix" class="icon-search"></image>
				<input type="text" placeholder="搜索经纪人昵称" v-model="nickName" class="search-inp">
			</view>
			<view class="flex item-center">
				<image src="@/static/svg/icon-input-clean.svg" mode="widthFix" :style="{width:'20px'}" @click="cleanText" v-if="nickName.length"></image>
				<view class="search-text" @click="searchNickName">搜索</view>
			</view>
		</view>
		<scroll-view scroll-y="true" :style="{'height':h}" @scrolltolower='scrolltolower' refresher-enabled='true'
			:refresher-triggered="triggered" @refresherrestore="onRestore" @refresherrefresh="onRefresh">
			<view v-for="item,index in list" v-if="list.length" class="agent-box" :key="item.id" @click="openDetail(item)">
				<view class="flex justify-between item-center">
					<view class="flex item-center">
						<image :src="item.avatar" mode="" class="img-avatar mr-8"></image>
						<view class="flex flex-col justify-between">
							<view>
								<text class="nick-name">{{item.nickName}}</text>
								<text class="tip">{{ item.groupName }}</text>
								<text v-if="item.commissionRate" class="tip yellow">专属{{ item.commissionRate }}%</text>
							</view>
							<view class="gray fs-12">注册时间：{{ item.createTime }}</view>
						</view>
					</view>
					<image class="size-20 self-start" src="@/pagesD/static/role/icon-dot.svg" @click.stop="action(item)"></image>
				</view>
				<view class="mt-20 flex">
					<view class="flex item-center flex-col w33">
						<view>{{ item.totalOrderCount }}</view>
						<view class="gray fs-12">累计订单</view>
					</view>
					<view class="flex item-center flex-col w33">
						<view>{{ item.totalSettleCommission }}</view>
						<view class="gray fs-12">累计佣金</view>
					</view>
					<view v-if="userStore.userInfo.agentLevel !== 1" class="flex item-center flex-col w33">
						<view>{{ item.inviteCount }}</view>
						<view class="gray fs-12">邀请人数</view>
					</view>
				</view>
			</view>
			<view v-else class="flex flex-col item-center justify-center" :style="{'height':h}">
				<image src="@/pagesD/static/role/icon-k-page.svg" mode="heightFix" style="height: 149px;"></image>
				<view class="k-text">没有您要找的人哦～</view>
			</view>
		</scroll-view>
		<GroupPopup ref="popup" :currentGroupId="params.groupId" @onSubmit="getList" />
		<sharePoster show="poster" :inviteData="inviteData" :groupData="groupData" ref="posterRef"></sharePoster>
		<InfoPop ref="infoPopRef" :detail="currentInfo" />
	</view>
</template>

<script setup>
	import sharePoster from '@/pagesD/components/share-poster/share-poster.vue';
	import InfoPop from './components/InfoPop.vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		ref,
		getCurrentInstance,
		watch,
		onMounted
	} from 'vue'
	import {
		pageGroupAgent,
		saveGroup
	} from '@/pagesD/api/group.js'
	import {
		useUserStore
	} from '@/stores/modules/user.js'
	import { inviteAgent, unBindAgent } from '@/api/business.js'
	import { mathHeight } from '@/utils/index.js'
	import GroupPopup from './components/GroupPopup.vue'
	import { onShareAppMessage } from '@dcloudio/uni-app';
	
	const userStore = useUserStore()
	const goBack = () => {
		getOpenerEventChannel.value.emit('reFreshPage','refresh')
		uni.navigateBack()
	}
	const h = ref(0)
	h.value = mathHeight(160)
	const triggered = ref(false)
	let list = ref([])
	let total = ref(0)
	let getOpenerEventChannel = ref(null)
	const currentInfo = ref()
	const groupData = ref('')
	const params = ref({
		groupId: '',
		pageNum: 1,
		pageSize: 15,
		nickName:''
	})
	const nickName = ref('')
	const popup = ref(null)
	const posterRef = ref()
	
	const inviteData = ref(null)
	const shareImg = ref('')
	
	const infoPopRef = ref()
	let name = ''
	let inviteCode = ''
	const openDetail = (item) => {
		currentInfo.value = item
		infoPopRef.value.showPop(true)
	}
	const getInviteAgent = async () => {
		let result = await inviteAgent({groupId: groupData.value.id})
		if(!result) return
		inviteData.value = result
		name = result.businessShortName
		inviteCode = result.inviteCode
	}
	
	const invite = async(item) => {
		if(!groupData.value.commissionRate && !userStore.userInfo.businessInfo){
			uni.showToast({
				icon: 'none',
				title: '请先设置分组佣金比例'
			})
			return
		}
		if(!inviteData.value){
			await getInviteAgent()
		}
		posterRef.value.showPopPoster(true)
	}
	
	const action = (item) => {
		uni.showActionSheet({
			itemList: ['解除关联', '移动分组'],
			success: function (res) {
				if(res.tapIndex === 0){
					uni.showModal({
						title: '',
						content: `确定解除关联？`,
						success: async function (res) {
							if (res.confirm) {
								let result = await unBindAgent({id:item.userId})
								if(result){
									uni.showToast({
										title: '解除成功',
										icon: 'none'
									})
									reFresh()
								}
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}else{
					popup.value && popup.value.showPopup(true, [item.userId])
				}
			},
			fail: function (res) {
				console.log(res.errMsg);
			}
		});
	}

	const getList = async () => {
		triggered.value = true
		uni.showLoading()
		let result = await pageGroupAgent(params.value)
		if (result) {
			list.value = params.value.pageNum == 1 ? result.list : (list.value).concat(result.list)
			total.value = result.total
		}
		uni.hideLoading()
		triggered.value = false
	}
	const scrolltolower = () => {
		if (list.value.length >= total.value) {
			return
		}
		params.value.pageNum = params.value.pageNum + 1
		getList()
	}
	const onRestore = () => {
		triggered.value = false; // 需要重置
	}
	const reFresh = () => {
		list.value = []
		params.value.pageNum = 1
		getList()
	}
	const cleanText = () => {
		params.value.nickName = ''
		nickName.value = ''
		reFresh()
	}
	const searchNickName = () => {
		params.value.nickName = nickName.value
		reFresh()
	}
	const onRefresh = () => {
		triggered.value = true
		reFresh()
	}
	onShareAppMessage((res) => {
		return {
			title: `${name}邀请您成为TA的经纪人`,
			path: `/applyPages/bindBusiness/bindBusiness?code=${inviteCode}&groupId=${params.value.groupId}`,
			imageUrl: res.target.dataset.filepath
		}
	})
	onLoad((query) => {
		getOpenerEventChannel.value = getCurrentInstance().ctx.getOpenerEventChannel();
		getOpenerEventChannel.value.on('acceptData',data => {
			groupData.value = data
			if(data.id){
				params.value.groupId = data.id
			}
			getList()
		})
	})
	onMounted(() => {
		uni.hideShareMenu()
		// getList()
	})
</script>

<style scoped lang="scss">
	.w33{
		width: 33%;
	}
	.page-box{
		width: 100vw;
		min-height: 100vh;
	}
	.bg-top{
		position: relative;
		top: 0;
		left: 0;
		overflow-y: auto;
		.image-bg{
			width: 100%;
		}
		.image-title{
			width: 316rpx;
			margin-top: 90rpx;
		}
		.image-tip{
			width: 356rpx;
			margin-top: 20px;
		}
		.img-right{
			width: 468rpx;
			position: absolute;
			left: 278rpx;
			top: 0;
		}
	}
	.top-tip{
		.invite-btn{
			border-radius: 15px;
			border: 1px solid #FA4543;
			padding: 4px 12px;
			text-align: center;
			color: #FA4543;
			background: #ffffff;
		}
	}

	.search-box {
		margin: 10px 16px;
		// box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.05);
		background-color: #ffffff;
		border-radius: 8px;
		padding: 0px 10px;
		height: 36px;

		.icon-search {
			height: 20px;
		}
		.search-inp {
			width: calc(100% - 80px);
			margin-left: 10px;
			font-size: 12px;
		}
	}
	
	.gray{
		color: rgba(51,51,51,0.6);
	}

	.agent-box {
		margin: 0 16px 12px;
		padding: 12px;
		background-color: #ffffff;
		border-radius: 8px;

		.img-avatar {
			width: 40px;
			height: 40px;
			border-radius: 50%;
		}

		.nick-name {
			font-size: 14px;
			font-weight: 400;
			line-height: 20px;
		}
		
		.tip{
			color: #16BE62;
			font-size: 10px;
			padding: 0 4px;
			border-radius: 4px;
			border: 1px solid #16BE62;
			margin-left: 4px;
			white-space: nowrap;
			&.yellow{
				color: #FCB513;
				border: 1px solid #FCB513;
			}
		}

		.total-settle {
			font-size: 12px;
			font-weight: 400;
			color: rgba(51, 51, 51, 0.6);
		}
	}
	.search-text{
		font-size: 14px;
		font-weight: 400;
		line-height: 22px;
		text-align: center;
		color: rgba(250, 69, 67, 1);
		margin-left: 10px;
	}
	.k-text{
		font-size: 12px;
		font-weight: 400;
		line-height: 17px;
		text-align: center;
		margin-top: 20px;
	}
</style>
